package com.sofwin.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sofwin.dto.ResourceDto;
import com.sofwin.pojo.SysResource;
import com.sofwin.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("system/resource")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @RequestMapping("data")
    public String data(Model model) throws JsonProcessingException {
//        List<ResourceDto> resources = resourceService.selectAllResources();
//        ObjectMapper mapper = new ObjectMapper();
//        String str = mapper.writeValueAsString(resources);
//        model.addAttribute("str",str);
        List<ResourceDto> resources = resourceService.selectAllResources();
        model.addAttribute("resources",resources);
        return "resource/data";
    }

    @RequestMapping("treeData")
    @ResponseBody
    public List treeData(Integer flag,Integer roleId){
        if(flag!=null && flag==1){
            // 将当前角色包含的，不包含的资源
//            List<ResourceDto> resources=resourceService.selectResourceByRoled(roleId);
            List<SysResource> resources = resourceService.selectResourceByRoleId(roleId);
            return resources;
        }
        List<SysResource> resources = resourceService.selectAllResources2();
        return resources;
    }
    @RequestMapping("save")
    @ResponseBody
    public Map save(SysResource resource){
        Map map = new HashMap();
       boolean status = resourceService.save(resource);
       map.put("status",status);
       return map;
    }
    @GetMapping("getResource")
    @ResponseBody
    public SysResource getResource(Integer id){
        SysResource resource=resourceService.selectById(id);
        return resource;
    }
    @GetMapping("delete")
    @ResponseBody
    public Map delete(Integer id){
        Map map = new HashMap();
        boolean status = resourceService.deleteById(id);
        map.put("status",status);
        return map;
    }
}
